"use strict";
// 参考: http://phantomjs.org/

var page = require('webpage').create(),
    system = require('system');

if (system.args.length === 1) {
    console.log('Usage: loadspeed.js <some UTRL>');
    phantom.exit();
}
var start_time = Date.now();
var url = system.args[1];

// page.onInitialized = function() {
//     console.log('======= onInitialized =======');
// };

page.onLoadStarted = function() {
    console.log('======= onLoadStarted =======');
};

page.onLoadFinished = function () {
    console.log('======= onLoadFinished =======');
};

page.onResourceRequested = function(requestData,  request) {
    console.log('-> ' + requestData['url']);
};

page.onResourceReceived = function(response) {
    // console.log('    #' + response.id + ', stage "' + response.stage + '"): ' + JSON.stringify(response));   
};

page.onResourceError = function(resourceError) {
    console.log('Unable to load resource (#' + resourceError.id + 'URL:' + resourceError.url + ')');
    console.log('Error code: ' + resourceError.errorCode + '. Description: ' + resourceError.errorString);
};

page.onResourceTimeout = function (request) {
    console.log('Response (#' + request.id + '): ' + JSON.stringify(request));
};

page.onConsoleMessage = function(msg) {
    console.log('[Console]: ' + msg);
};

page.onCallback = function(msg) {
    console.log('Received bu the "phantom" main context: ' + msg);
    return 'Copy that';
};

function waitFor(testFx, onReady, onTimeOut, timeOutMillis) {
    var start = new Date().getTime();
    var isReady = false;
    timeOutMillis = timeOutMillis ? timeOutMillis : 5000;       // default timeout: 5s

    var interval = setInterval(function() {
        if ((new Date().getTime() - start < timeOutMillis) && (!isReady)) {
            isReady = testFx();
        } else {
            clearInterval(interval);
            if (!isReady) {
                console.log('wait for: Time out.');
                onTimeOut();
            } else {
                console.log('wait for: Is ready.');
                onReady();
            }
        }
    }, 200);
};

console.log('Loading: ' + url);
page.open(url, function(status) {
    if (status !== 'success') {
        console.log('FAIL to load the address!');
    } else {
        var end_time = Date.now();
        console.log('Total time: ' + (end_time - start_time));

        waitFor(function() {
            return page.evaluate(function() {
                return isInitFinish;
                // return $('#run').length > 0;
            });
        }, function() {
            page.render('test.png');
            phantom.exit(0);
        }, function() {
            phantom.exit(-1);
        });

        // var res = page.evaluate(function () {
        //     var callbackResponse = window.callPhantom("Hi");
        //     console.log('Recived by the "page" context: ' + callbackResponse);
        //     return 'OK';
        // });
        // console.log(res);

        // page.render('test.png');
        // phantom.exit();
    }
});
